﻿using CommunicaionLib.Model;
using PLCLib;
using PLCLib.Mvvm;
using PLC通讯框架开发.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PLC通讯框架开发.ViewModel
{
    public class MainViewModel : ObservableObject
    {
        /// <summary>
        /// 属性才可以帮点XAML前端
        /// </summary>
        public OrmonPlc OrmonPlc { get; set; } = new OrmonPlc();

        private ObservableCollection<Message> messagesList = new ObservableCollection<Message>();

        public ObservableCollection<Message> MessagesList 
        {
            get { return messagesList; }
            set {  messagesList = value; RaisPropertyChanged(); }
        }

        private ObservableCollection<Message> byteList = new ObservableCollection<Message>();

        public ObservableCollection<Message> ByteList
        {
            get { return byteList; }
            set { byteList = value; RaisPropertyChanged(); }
        }

        public MainViewModel()
        {
            OrmonPlc.OnError += OrmonPlc_OnMessage;
            OrmonPlc.OnMessage += OrmonPlc_OnMessage;
            OrmonPlc.OnSend += OrmonPlc_OnSend;
            OrmonPlc.OnReceived += OrmonPlc_OnReceived;
        }

        private void OrmonPlc_OnReceived(object arg, DataPackage Package)
        {
            Message message = new Message();
            message.DateTime = Package.ReceiveTime;
            message.Content = "接收:" + Package.ReceiveBufferToString ;
            App.Current.Dispatcher.Invoke(() => ByteList.Insert(0, message));
        }

        private void OrmonPlc_OnSend(object arg, CommunicaionLib.Model.DataPackage Package)
        {
            Message message = new Message();
            message.DateTime = Package.SendTime;
            message.Content = "下发:" + Package.SendBufferToString;
            App.Current.Dispatcher.Invoke(() => ByteList.Insert(0, message));

        }

        private void OrmonPlc_OnMessage(object sender, PLCLib.Model.PlcEventArgs arg)
        {
            Message message = new Message();
            message.DateTime = DateTime.Now;
            message.Content = arg.Message;
            App.Current.Dispatcher.Invoke(() =>
            {
                MessagesList.Insert(0,message);
            });

        }


        /// <summary>
        /// 设备再连接提示（只许连接一个）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="arg"></param>
        public void ReconnectTip(object sender, PLCLib.Model.PlcEventArgs arg)
        {
            Message message = new Message();
            message.DateTime = DateTime.Now;
            message.Content = arg.Message;
            App.Current.Dispatcher.Invoke(() =>
            {
                MessagesList.Insert(0, message);
            });
        }

    }
}
